package com.ruoyi.web.controller.course;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysPeriod;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.course.service.ISysPeriodService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 课时信息
 * 
 * @author YJF
 */
@RestController
@RequestMapping("/course/period")
public class SysPeriodController extends BaseController
{
    @Autowired
    private ISysPeriodService periodService;

    /**
     * 获取课时列表
     */
    @PreAuthorize("@ss.hasPermi('course:period:list')")
    @GetMapping("/list")
    public AjaxResult list(SysPeriod period)
    {
        List<SysPeriod> periods = periodService.selectPeriodList(period);
        return AjaxResult.success(periods);
    }

    /**
     * 查询课时列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('course:period:list')")
    @GetMapping("/list/exclude/{periodId}")
    public AjaxResult excludeChild(@PathVariable(value = "periodId", required = false) Long periodId)
    {
        List<SysPeriod> periods = periodService.selectPeriodList(new SysPeriod());
        Iterator<SysPeriod> it = periods.iterator();
        while (it.hasNext())
        {
            SysPeriod d = (SysPeriod) it.next();
            if (d.getPeriodId().intValue() == periodId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), periodId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(periods);
    }

    /**
     * 根据课时编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:period:query')")
    @GetMapping(value = "/{periodId}")
    public AjaxResult getInfo(@PathVariable Long periodId)
    {
        periodService.checkPeriodDataScope(periodId);
        return AjaxResult.success(periodService.selectPeriodById(periodId));
    }

    /**
     * 获取课时下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysPeriod period)
    {
        List<SysPeriod> periods = periodService.selectPeriodList(period);
        return AjaxResult.success(periodService.buildPeriodTreeSelect(periods));
    }

    /**
     * 加载对应角色课时列表树
     */
    @GetMapping(value = "/rolePeriodTreeselect/{roleId}")
    public AjaxResult rolePeriodTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysPeriod> periods = periodService.selectPeriodList(new SysPeriod());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("periods", periodService.buildPeriodTreeSelect(periods));
        return ajax;
    }

    /**
     * 新增课时
     */
    @PreAuthorize("@ss.hasPermi('course:period:add')")
    @Log(title = "课时管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPeriod period)
    {
        if (UserConstants.NOT_UNIQUE.equals(periodService.checkPeriodNameUnique(period)))
        {
            return AjaxResult.error("新增课时'" + period.getPeriodName() + "'失败，课时名称已存在");
        }
        period.setCreateBy(getUsername());
        return toAjax(periodService.insertPeriod(period));
    }

    /**
     * 修改课时
     */
    @PreAuthorize("@ss.hasPermi('course:period:edit')")
    @Log(title = "课时管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPeriod period)
    {
        Long periodId = period.getPeriodId();
        periodService.checkPeriodDataScope(periodId);
        if (UserConstants.NOT_UNIQUE.equals(periodService.checkPeriodNameUnique(period)))
        {
            return AjaxResult.error("修改课时'" + period.getPeriodName() + "'失败，课时名称已存在");
        }
        else if (period.getParentId().equals(periodId))
        {
            return AjaxResult.error("修改课时'" + period.getPeriodName() + "'失败，上级课时不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, period.getStatus()) && periodService.selectNormalChildrenPeriodById(periodId) > 0)
        {
            return AjaxResult.error("该课时包含未停用的子课时！");
        }
        period.setUpdateBy(getUsername());
        return toAjax(periodService.updatePeriod(period));
    }

    /**
     * 删除课时
     */
    @PreAuthorize("@ss.hasPermi('course:period:remove')")
    @Log(title = "课时管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{periodId}")
    public AjaxResult remove(@PathVariable Long periodId)
    {
        if (periodService.hasChildByPeriodId(periodId))
        {
            return AjaxResult.error("存在下级课时,不允许删除");
        }
        if (periodService.checkPeriodExistCourse(periodId))
        {
            return AjaxResult.error("课时存在课程,不允许删除");
        }
        periodService.checkPeriodDataScope(periodId);
        return toAjax(periodService.deletePeriodById(periodId));
    }
}
